<template>
  <div class="add-patient-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </div>
        <div class="header-title">添加就诊人</div>
        <div class="home-btn" @click="$router.push('/')">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9,22 9,12 15,12 15,22"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content">
      <!-- 头像上传 -->
      <div class="avatar-section">
        <div class="avatar-upload" @click="triggerFileInput">
          <div class="avatar-placeholder" v-if="!patientForm.avatar">
            <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#1877F2" stroke-width="2">
              <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
              <circle cx="12" cy="13" r="4"/>
            </svg>
            <span>点击上传头像</span>
          </div>
          <img 
            v-else 
            :src="patientForm.avatar" 
            alt="头像" 
            class="avatar-preview"
            @load="() => console.log('头像预览加载成功')"
            @error="() => console.log('头像预览加载失败')"
          />
          <input 
            ref="fileInput" 
            type="file" 
            accept="image/*" 
            @change="handleFileUpload" 
            style="display: none;"
          />
        </div>
      </div>

      <!-- 表单 -->
      <form @submit.prevent="submitForm" class="patient-form">
        <div class="form-group">
          <label class="form-label">
            就诊人姓名 <span class="required">*</span>
          </label>
          <input 
            v-model="patientForm.name" 
            type="text" 
            placeholder="请输入与就诊人姓名"
            class="form-input"
            :class="{ 'error': errors.name }"
            @blur="validateField('name')"
          />
          <span v-if="errors.name" class="error-message">{{ errors.name }}</span>
        </div>

        <div class="form-group">
          <label class="form-label">
            证件号码 <span class="required">*</span>
          </label>
          <input 
            v-model="patientForm.idCard" 
            type="text" 
            placeholder="请输入证件号码"
            class="form-input"
            :class="{ 'error': errors.idCard }"
            @blur="validateField('idCard')"
          />
          <span v-if="errors.idCard" class="error-message">{{ errors.idCard }}</span>
        </div>

        <div class="form-group">
          <label class="form-label">
            出生日期 <span class="required">*</span>
          </label>
          <input 
            v-model="patientForm.birthDate" 
            type="date" 
            class="form-input"
            :class="{ 'error': errors.birthDate }"
            @blur="validateField('birthDate')"
          />
          <span v-if="errors.birthDate" class="error-message">{{ errors.birthDate }}</span>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label class="form-label">性别</label>
            <select 
              v-model="patientForm.gender" 
              class="form-input"
              :class="{ 'error': errors.gender }"
              @blur="validateField('gender')"
            >
              <option value="">请选择</option>
              <option value="male">男</option>
              <option value="female">女</option>
            </select>
            <span v-if="errors.gender" class="error-message">{{ errors.gender }}</span>
          </div>

          <div class="form-group">
            <label class="form-label">血型</label>
            <select 
              v-model="patientForm.bloodType" 
              class="form-input"
            >
              <option value="">请选择</option>
              <option value="A">A型</option>
              <option value="B">B型</option>
              <option value="AB">AB型</option>
              <option value="O">O型</option>
            </select>
          </div>
        </div>

        <div class="form-row">
          <div class="form-group">
            <label class="form-label">婚姻状况</label>
            <select 
              v-model="patientForm.maritalStatus" 
              class="form-input"
            >
              <option value="">请选择</option>
              <option value="single">未婚</option>
              <option value="married">已婚</option>
              <option value="divorced">离异</option>
              <option value="widowed">丧偶</option>
            </select>
          </div>

          <div class="form-group">
            <label class="form-label">专程就医</label>
            <select 
              v-model="patientForm.specializedTreatment" 
              class="form-input"
            >
              <option value="">请选择</option>
              <option value="yes">是</option>
              <option value="no">否</option>
            </select>
          </div>
        </div>

        <div class="form-group">
          <label class="form-label">
            手机号 <span class="required">*</span>
          </label>
          <input 
            v-model="patientForm.phone" 
            type="tel" 
            placeholder="请输入手机号"
            class="form-input"
            :class="{ 'error': errors.phone }"
            @blur="validateField('phone')"
          />
          <span v-if="errors.phone" class="error-message">{{ errors.phone }}</span>
        </div>

        <div class="form-group">
          <label class="form-label">紧急联系人</label>
          <input 
            v-model="patientForm.emergencyContact" 
            type="text" 
            placeholder="请输入紧急联系人姓名"
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label class="form-label">紧急联系人电话</label>
          <input 
            v-model="patientForm.emergencyPhone" 
            type="tel" 
            placeholder="请输入紧急联系人电话"
            class="form-input"
          />
        </div>

        <div class="form-group">
          <label class="form-label">地址</label>
          <textarea 
            v-model="patientForm.address" 
            placeholder="请输入详细地址"
            class="form-textarea"
            rows="3"
          ></textarea>
        </div>

        <div class="form-group">
          <label class="form-label">备注</label>
          <textarea 
            v-model="patientForm.notes" 
            placeholder="请输入备注信息"
            class="form-textarea"
            rows="3"
          ></textarea>
        </div>
      </form>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-button">
      <button 
        class="confirm-btn" 
        :class="{ 'disabled': !isFormValid || submitting }"
        @click="submitForm"
        :disabled="!isFormValid || submitting"
      >
        <span v-if="submitting">提交中...</span>
        <span v-else>确定</span>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { patientsApi, localPatientsStorage, type CreatePatientRequest } from '../../api/patients'

const router = useRouter()

interface PatientForm {
  name: string
  idCard: string
  birthDate: string
  gender: string
  bloodType: string
  maritalStatus: string
  specializedTreatment: string
  phone: string
  emergencyContact: string
  emergencyPhone: string
  address: string
  notes: string
  avatar: string
}

interface FormErrors {
  name?: string
  idCard?: string
  birthDate?: string
  gender?: string
  phone?: string
}

const patientForm = ref<PatientForm>({
  name: '',
  idCard: '',
  birthDate: '',
  gender: '',
  bloodType: '',
  maritalStatus: '',
  specializedTreatment: '',
  phone: '',
  emergencyContact: '',
  emergencyPhone: '',
  address: '',
  notes: '',
  avatar: ''
})

const errors = ref<FormErrors>({})
const submitting = ref(false)
const fileInput = ref<HTMLInputElement>()

// 表单验证规则
const validationRules = {
  name: (value: string) => {
    if (!value) return '请输入就诊人姓名'
    if (value.length < 2) return '姓名至少2个字符'
    if (value.length > 20) return '姓名不能超过20个字符'
    return ''
  },
  idCard: (value: string) => {
    if (!value) return '请输入证件号码'
    if (!/^\d{17}[\dXx]$/.test(value)) return '请输入正确的身份证号码'
    return ''
  },
  birthDate: (value: string) => {
    if (!value) return '请选择出生日期'
    const today = new Date()
    const birthDate = new Date(value)
    if (birthDate > today) return '出生日期不能晚于今天'
    return ''
  },
  phone: (value: string) => {
    if (!value) return '请输入手机号'
    if (!/^1[3-9]\d{9}$/.test(value)) return '请输入正确的手机号码'
    return ''
  },
  gender: (value: string) => {
    if (!value) return '请选择性别'
    if (!['male', 'female'].includes(value)) return '请选择正确的性别'
    return ''
  }
}

// 验证单个字段
const validateField = (field: keyof FormErrors) => {
  const rule = validationRules[field]
  if (rule) {
    const error = rule(patientForm.value[field])
    if (error) {
      errors.value[field] = error
    } else {
      delete errors.value[field]
    }
  }
}

// 验证整个表单
const validateForm = () => {
  Object.keys(validationRules).forEach(field => {
    validateField(field as keyof FormErrors)
  })
  return Object.keys(errors.value).length === 0
}

// 表单是否有效
const isFormValid = computed(() => {
  return patientForm.value.name && 
         patientForm.value.idCard && 
         patientForm.value.birthDate && 
         patientForm.value.gender &&
         patientForm.value.phone &&
         Object.keys(errors.value).length === 0
})

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value?.click()
}

// 处理文件上传
const handleFileUpload = (event: Event) => {
  const target = event.target as HTMLInputElement
  const file = target.files?.[0]
  
  if (file) {
    console.log('选择的文件:', file.name, file.type, file.size)
    
    // 验证文件类型和大小
    if (!file.type.startsWith('image/')) {
      showToast('请选择图片文件')
      return
    }
    
    if (file.size > 5 * 1024 * 1024) { // 5MB
      showToast('图片大小不能超过5MB')
      return
    }
    
    // 读取文件并预览
    const reader = new FileReader()
    reader.onload = (e) => {
      const result = e.target?.result as string
      console.log('文件读取成功，数据长度:', result.length)
      patientForm.value.avatar = result
      console.log('头像已设置:', patientForm.value.avatar.substring(0, 100) + '...')
    }
    reader.onerror = () => {
      console.error('文件读取失败')
      showToast('文件读取失败')
    }
    reader.readAsDataURL(file)
  }
}

// 提交表单
const submitForm = async () => {
  if (!validateForm()) {
    showToast('请完善必填信息')
    return
  }
  
  submitting.value = true
  
  try {
    // 创建FormData对象
    const formData = new FormData()
    
    // 添加基本信息
    formData.append('name', patientForm.value.name)
    formData.append('idCard', patientForm.value.idCard)
    formData.append('birthDate', new Date(patientForm.value.birthDate).toISOString())
    formData.append('gender', patientForm.value.gender)
    formData.append('phone', patientForm.value.phone)
    
    // 添加可选信息
    if (patientForm.value.bloodType) {
      formData.append('bloodType', patientForm.value.bloodType)
    }
    if (patientForm.value.maritalStatus) {
      formData.append('maritalStatus', patientForm.value.maritalStatus)
    }
    if (patientForm.value.specializedTreatment) {
      formData.append('specializedTreatment', patientForm.value.specializedTreatment)
    }
    if (patientForm.value.emergencyContact) {
      formData.append('emergencyContact', patientForm.value.emergencyContact)
    }
    if (patientForm.value.emergencyPhone) {
      formData.append('emergencyPhone', patientForm.value.emergencyPhone)
    }
    if (patientForm.value.address) {
      formData.append('address', patientForm.value.address)
    }
    if (patientForm.value.notes) {
      formData.append('notes', patientForm.value.notes)
    }
    
    // 添加默认用户ID
    formData.append('userId', '507f1f77bcf86cd799439011')
    
    // 处理头像文件
    if (patientForm.value.avatar && patientForm.value.avatar.startsWith(''
  
  console.log('AddPatient页面初始化完成，默认头像长度:', patientForm.value.avatar.length)
})
</script>

<style scoped>
.add-patient-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 100px;
}

.header {
  background: #1877F2;
  padding: 0 20px;
  padding-top: env(safe-area-inset-top);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
}

.back-btn, .home-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.2s;
}

.back-btn:hover, .home-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.content {
  padding: 20px;
}

/* 头像上传 */
.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 24px;
}

.avatar-upload {
  width: 100px;
  height: 100px;
  border: 2px dashed #ddd;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
  overflow: hidden;
  background: white;
}

.avatar-upload:hover {
  border-color: #1877F2;
  background: #f8fbff;
}

.avatar-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  color: #1877F2;
  font-size: 12px;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 50%;
}

/* 表单 */
.patient-form {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-label {
  display: block;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.required {
  color: #ff4757;
}

.form-input, .form-textarea {
  width: 100%;
  border: none;
  border-bottom: 1px solid #ddd;
  padding: 12px 0;
  font-size: 14px;
  outline: none;
  transition: border-color 0.2s;
  background: transparent;
}

.form-input:focus, .form-textarea:focus {
  border-color: #1877F2;
}

.form-input.error {
  border-color: #ff4757;
}

.form-textarea {
  resize: vertical;
  min-height: 80px;
}

.error-message {
  color: #ff4757;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

/* 底部按钮 */
.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.confirm-btn {
  width: 100%;
  height: 48px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.confirm-btn:hover:not(.disabled) {
  background: #1565c0;
}

.confirm-btn.disabled {
  background: #ccc;
  color: #999;
  cursor: not-allowed;
}

/* 轻提示 */
.toast-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10000;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
}

.toast-message.show {
  opacity: 1;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .content {
    padding: 16px;
  }
  
  .patient-form {
    padding: 16px;
  }
  
  .form-row {
    grid-template-columns: 1fr;
    gap: 0;
  }
  
  .avatar-upload {
    width: 80px;
    height: 80px;
  }
}
</style> 